﻿using System;
using System.Collections.Generic;
using System.Text;
using Graffiti.Core;
using CookComputing.XmlRpc;

namespace GraffitiExtras.Plugins.Pingomatic
{
    public class Pingomatic : GraffitiEvent
    {
        #region EditableForm members

        public override string Name
        {
            get
            {
                return "Pingomatic";
            }
        }

        public override string Description
        {
            get
            {
                return "Pingomatic ping plug-in for Graffiti by <a href=\"http://nayyeri.net\">" +
                    "Keyvan Nayyeri</a>.";
            }
        }

        public override bool IsEditable
        {
            get
            {
                return false;
            }
        }

        #endregion

        #region GraffitiEvent members

        public override void Init(GraffitiApplication ga)
        {
            ga.AfterInsert += new DataObjectEventHandler(ga_AfterInsert);
        }

        void ga_AfterInsert(DataBuddyBase dataObject, EventArgs e)
        {
            Post post = dataObject as Post;

            try
            {
                if (post != null)
                {
                    if (post.IsPublished && post.Published > DateTime.Now.Subtract(new TimeSpan(5, 0, 0, 0, 0)))
                    {
                        string blogTitle = SiteSettings.Get().Title;
                        string blogUrl = new Macros().FullUrl(new Urls().Home);

                        UpdateResponse response = WeblogsRPC.Ping(blogTitle, blogUrl);

                        if (response.flerror)
                        {
                            Log.Error("Pingomatic Plug-In", response.message);
                        }
                        else
                        {
                            Log.Info("Pingomatic Plug-In", response.message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Pingomatic Plug-In", ex.Message + ex.StackTrace);
            }
        }

        #endregion
    }
}
